package root.electronclass.electronclass.grade.record

import androidx.lifecycle.*
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.grade.model.ClassRecord
import root.electronclass.electronclass.grade.repository.ClassRepository
import kotlinx.coroutines.launch

/**
 *
 * @author Lokiy
 * @date 2023/2/4 14:07
 */
class ClassRecordViewModel : ViewModel() {

    private val _data = MediatorLiveData<Pair<Int, List<ClassRecord>>>()
    val data: LiveData<Pair<Int, List<ClassRecord>>> = _data

    private var pageIndex = 1

    private var text: String = ""
    private var type: Int = 1//0-全部 1-近7天 2-近30天 3-一学期

    init {
        load(page = 1)
    }

    /**
     * 加载班级荣誉
     */
    fun load(type: Int = this.type, text: String = this.text, page: Int = pageIndex + 1) {
        this.text = text
        this.type = type
        pageIndex = page
        loadData(type, text)
    }

    private fun loadData(type: Int, text: String) {
        viewModelScope.launch(CoroutineExceptionHandler { pageIndex = (pageIndex - 1).coerceAtLeast(1) }) {
            val list = ClassRepository.getClassRecord(pageIndex, type, text)
            _data.value = pageIndex to list
            if (list.isEmpty()) {
                pageIndex--
            }
        }
    }

}
